package com.bootdo.per.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.per.domain.PersonDO;
import com.bootdo.per.domain.ScoreDO;
import com.bootdo.per.domain.TeamDO;
import com.bootdo.per.service.ManagerService;
import com.bootdo.per.service.PersonService;
import com.bootdo.per.service.ScoreService;
import com.bootdo.per.service.TeamService;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.service.DeptService;
import com.bootdo.common.exception.BDException;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ExcelUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 
 * 
 * @author readke
 * @email 1992lcg@163.com
 * @date 2018-06-05 17:51:30
 */

@Controller
@RequestMapping("/per/score")
public class ScoreController {
	@Autowired
	private ScoreService scoreService;
	@Autowired
	private TeamService teamService;
	@Autowired
	private PersonService personService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private ManagerService managerService;
	@GetMapping()
	@RequiresPermissions("per:score:score")
	String Score(Model model) {
		String status = managerService.list(null).get(0).getStatus();
		model.addAttribute("mStatus", status);
		DeptDO dept = deptService.getByPID(0L).get(0);
		Map<String, Object> map = new HashMap<>();
		map.put("parentId", dept.getDeptId());
		model.addAttribute("deptList", deptService.list(map));

		return "per/score/score";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("per:score:score")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<Map<String, Object>> scoreList = scoreService.list(query);
		int total = scoreService.count(query);
		PageUtils pageUtils = new PageUtils(scoreList, total);
		return pageUtils;
	}

	@PostMapping("/result")
	@ResponseBody
	@RequiresPermissions("per:score:result")
	R result() {
		Map<String, Object> map = new HashMap<>();
		map.put("year", DateUtils.getYear());
		map.put("month", DateUtils.getMonth());
		List<Map<String, Object>> teamList = teamService.getTeamResult(map);
		List<Map<String, Object>> personList = personService.getPersonResult(map);
		teamList.addAll(personList);
		if (teamList == null || teamList.size() == 0) {
			return R.error(1, "暂无本月的评分记录,请评分结束后再进行此操作");
		}
		if (scoreService.saveResult(teamList, map) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequestMapping("/export")
	public void export(@RequestParam Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) {
		Workbook wb = null;
		String fileName =null;
		switch ((String)params.get("type")) {
			case "year":
				fileName = "资产负债管理部年度积分表.xlsx";
				wb = getByYear(params);
				break;
			case "quarter":
				fileName = "资产负债管理部季度积分表.xlsx";		
				wb = getByQuarter(params);
				break;
			case "month":
				fileName = "资产负债管理部月度积分表.xlsx";
				wb = getByMonth(params);
				break;
		}
		 
		// 响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			throw new BDException("导出文件失败");
		}
	}

	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "iso8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=iso8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private Workbook getByQuarter(Map<String, Object> params) {
		// 获取数据
		List<Map<String, Object>> list = scoreService.list(params);
		if(list == null || list.size() == 0){
			throw new BDException("导出数据为空,创建导出文件失败");
		}

		// excel标题
		String[] title = { "姓名", "所属团队", "得分", "年份", "季度" };

		// String fileName = "资产负债管理部年度积分表.xlsx";
		// String fileName = "资产负债管理部月度积分表.xlsx";

		String sheetName = "季度评分";

		String[][] content = new String[list.size()][title.length];
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			content[i][0] = String.valueOf(map.get("NAME"));
			content[i][1] = String.valueOf(map.get("ORG"));
			content[i][2] = String.valueOf(map.get("FINAL_SCORE"));
			content[i][3] = String.valueOf(map.get("YEAR"));
			content[i][4] = String.valueOf(map.get("QUARTER"));

		}
		return ExcelUtil.getWorkbook(sheetName, title, content, null);
	}

	private Workbook getByYear(Map<String, Object> params) {
		// 获取数据
		List<Map<String, Object>> list = scoreService.list(params);
		if(list == null || list.size() == 0){
			throw new BDException("导出数据为空,创建导出文件失败");
		}
		// excel标题
		String[] title = { "姓名", "所属团队", "得分", "年份" };
		String sheetName = "年度评分";
		String[][] content = new String[list.size()][title.length];
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			content[i][0] = String.valueOf(map.get("NAME"));
			content[i][1] = String.valueOf(map.get("ORG"));
			content[i][2] = String.valueOf(map.get("FINAL_SCORE"));
			content[i][3] = String.valueOf(map.get("YEAR"));

		}
		return ExcelUtil.getWorkbook(sheetName, title, content, null);
	}

	private Workbook getByMonth(Map<String, Object> params) {
		// 获取数据
		List<Map<String, Object>> list = scoreService.list(params);
		if(list == null || list.size() == 0){
			throw new BDException("导出数据为空,创建导出文件失败");
		}
		// excel标题
		String[] title = { "姓名", "所属团队", "得分", "年份", "月份" };
		String sheetName = "年度评分";
		String[][] content = new String[list.size()][title.length];
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			content[i][0] = String.valueOf(map.get("NAME"));
			content[i][1] = String.valueOf(map.get("ORG"));
			content[i][2] = String.valueOf(map.get("FINAL_SCORE"));
			content[i][3] = String.valueOf(map.get("YEAR"));
			content[i][4] = String.valueOf(map.get("MONTH"));

		}
		return ExcelUtil.getWorkbook(sheetName, title, content, null);
	}
}
